uniform sampler2D lines, depthTexture;
uniform vec2 screenSize;
uniform float radius;
uniform vec4 color;
uniform int threshold;
uniform int gaussian;
           
void main(void) { 
 
  float pixel;
  float depth;
  float minDepth= 1.0;
  int foreground= 0; 
  float alpha= 0.0;

  float i, j;

  float radiusSquared= radius*radius;
  
  float centerDepth= texture2D(depthTexture, gl_FragCoord.xy/screenSize).r;

  if(gaussian==0){
    for(i=-radius; i<=radius; i++){ 
      for(j=-radius; j<=radius; j++){
        if(i*i+j*j<=radiusSquared){
	  pixel= texture2D(lines, (gl_FragCoord.xy+vec2(i, j))/screenSize).r;
          if(pixel>alpha) alpha= pixel;
          if(pixel!=0.0) foreground++;
        }
        if(centerDepth==1.0){
	  if(i*i+j*j>radiusSquared){	  
            depth= texture2D(depthTexture, (gl_FragCoord.xy+vec2(i, j))/screenSize).r;
            if(depth<minDepth) minDepth= depth;
	  }
        }
      }	
    }	 
  } 
  else{   
    for(i=-radius-1.0; i<=radius+1.0; i++){ 
      for(j=-radius-1.0; j<=radius+1.0; j++){
        if(i*i+j*j<=radiusSquared){
	  pixel= texture2D(lines, (gl_FragCoord.xy+vec2(i, j))/screenSize).r;
          if(pixel>alpha) alpha= pixel;
          if(pixel!=0.0) foreground++;
        }
        if(centerDepth==1.0){
          if(gaussian==3){
	    if(i*i+j*j>radiusSquared && i*i+j*j<=radiusSquared+16.0){	  
              depth= texture2D(depthTexture, (gl_FragCoord.xy+vec2(i, j))/screenSize).r;
              if(depth<minDepth) minDepth= depth;
	    }
          } 
	  else{
	    if(i*i+j*j>radiusSquared && i*i+j*j<=radiusSquared+25.0){	  
              depth= texture2D(depthTexture, (gl_FragCoord.xy+vec2(i, j))/screenSize).r;
              if(depth<minDepth) minDepth= depth;
            }
	  }
        }
      }	
    }	 
  }
           
  if(foreground>threshold){
    gl_FragColor= vec4(color.rgb, alpha);
    if(centerDepth==1.0) gl_FragDepth= minDepth;
    else gl_FragDepth= gl_FragCoord.z;
  }  
  else{
    discard;
  }

//gl_FragColor= vec4(texture2D(lines, (gl_FragCoord.xy)/screenSize).xyz, 1.0);
}